import bge

def main():
    sensitivity = 0.0005

    controller = bge.logic.getCurrentController()
    camera = controller.owner
    
    gameScreen = getGameWindow()
    
    mouseMove = getMouseMove(gameScreen, controller, camera)
    
    useCameraLook(controller, mouseMove, sensitivity)
    
    centerCursor(controller, gameScreen)

def getGameWindow():
    width = bge.render.getWindowWidth()
    height = bge.render.getWindowHeight()
    
    return (width, height)

def getMouseMove(gameScreen, controller, camera):
    mouse = controller.sensors["CameraControl_SEN"]
    width = gameScreen[0]
    height = gameScreen[1]
    
    x = width/2 - mouse.position[0]
    y = height/2 - mouse.position[1]
    
    if not 'cameraInit' in camera:
        camera['cameraInit'] = True
        x = 0
        y = 0
        
    return (x,y)
    
def useCameraLook(controller, mouseMove, sensitivity):
    upDown = mouseMove[1] * sensitivity
    leftRight = mouseMove[0] * sensitivity
    
    actLeftRight = controller.actuators["LookLeftRight_ACT"]
    actUpDown = controller.actuators["LookUpDown_ACT"]
    
    actLeftRight.dRot = [0.0, 0.0, leftRight]
    actLeftRight.useLocalDRot = False
    
    actUpDown.dRot = [upDown, 0.0, 0.0]
    actUpDown.useLocalDRot = True
    
    controller.activate(actLeftRight)
    controller.activate(actUpDown) 

# define center mouse cursor
def centerCursor(controller, gameScreen):
    width = gameScreen[0]
    height = gameScreen[1]
    
    mouse = controller.sensors["CameraControl_SEN"]
    pos = mouse.position 

    if pos != [int(width/2), int(height/2)]:
        bge.render.setMousePosition(int(width/2), int(height/2))
        
    else:
        actLeftRight = controller.actuators["LookLeftRight_ACT"]
        actUpDown = controller.actuators["LookUpDown_ACT"]
        
        controller.deactivate(actLeftRight)
        controller.deactivate(actUpDown) 

main()
    